package MainControl;

import Instrument.TestingMachine;
import Model.Dryer;
import Model.Pulsator;
import Tool.*;
import Model.Roller;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MainControl implements Runnable {
    public HashMap<Integer, TestingMachine> machines = new HashMap<>();
    public HashMap<Integer, OutputStream> commandWriters = new HashMap<>();
    public HashMap<Integer, InputStream> dataReaders = new HashMap<>();
    public HashMap<Integer, Socket> connections = new HashMap<>();
    private Socket dataBackSocket;
    private OutputStream databackStream;
    private OutputStream databackStreamHex;
    private PrintWriter databackWriter;
    private volatile static MainControl mainControl;
    private ServerSocket serverSocketHex;
    private Socket socketHex;
    boolean flagTrue = false;//轮循查报警跟6D


    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String remark = "";//定义波轮还是滚筒，添加控制台信息使用

    //设置重新初试话Socket,其中machineNo为configure中的TotalTestUnitID的value
    public synchronized void reInit(Integer machineNo) {
        String ipAndPort = GlobalVariable.ips.get(String.valueOf(machineNo));
        String ip = ipAndPort.split(":")[0];
        Integer port = Integer.valueOf(ipAndPort.split(":")[1]);
        Socket tempSocket = null;
        OutputStream tempWriter = null;
        InputStream tempReader = null;
        try {
            tempSocket = new Socket();
            tempSocket.connect(new InetSocketAddress(ip, port), 200);
            tempSocket.setSoTimeout(200);
            tempSocket.setKeepAlive(true);
        } catch (Exception e) {
            e.printStackTrace();
            WriteLog.write(e.toString(), machineNo);
        }
        connections.remove(machineNo);
        connections.put(machineNo, tempSocket);
        try {
            tempWriter = tempSocket.getOutputStream();
            if (tempWriter == null) {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            WriteLog.write(e.toString(), machineNo);
        }
        commandWriters.remove(machineNo);
        commandWriters.put(machineNo, tempWriter);

        try {
            tempReader = tempSocket.getInputStream();
            if (tempReader == null) {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            WriteLog.write(e.toString(), machineNo);
        }
        dataReaders.remove(machineNo);
        dataReaders.put(machineNo, tempReader);
        System.out.println(format.format(new Date()) + "--------------台位" + machineNo + "初始化结束---------------");
        WriteLog.write(format.format(new Date()) + "--------------台位" + machineNo + "初始化结束---------------", machineNo);
    }

    //创建单例
    public static MainControl getMainControl() {
        if (mainControl == null) {
            synchronized (MainControl.class) {
                if (mainControl == null) {
                    mainControl = new MainControl();
                }

            }
        }
        return mainControl;
    }

    //关闭socket
    public synchronized void closeSocket(Integer machineNum) {
        try {
            if (dataReaders.get(machineNum) != null) {
                dataReaders.get(machineNum).close();
                dataReaders.remove(machineNum);
            }
            if (commandWriters.get(machineNum) != null) {
                commandWriters.get(machineNum).close();
                commandWriters.remove(machineNum);
            }
            if (connections.get(machineNum) != null) {
                connections.get(machineNum).close();
                connections.remove(machineNum);
            }
        } catch (IOException e) {
            e.printStackTrace();
            WriteLog.write("closeSocket方法有错误", machineNum);
            WriteLog.write(e.toString(), machineNum);
        }

    }

    //接收消息
    public synchronized void getMsg() {
        String collectedValue = "";
        String result7D = "";
        String date7DTemp = "";
        String alarm = "";
        String resultHex = "";
        int readCount = 0;
        String roller7D = null;//完整的滚筒7d数据
        String waterHeight = null;//水位
        byte[] readBuffer = new byte[4096];
        //关机
        byte powerOff[] = new byte[15];
        powerOff[0] = (byte) 0xFF;
        powerOff[1] = (byte) 0xFF;
        powerOff[2] = (byte) 0x0C;
        powerOff[3] = (byte) 0x00;
        powerOff[4] = (byte) 0x00;
        powerOff[5] = (byte) 0x00;
        powerOff[6] = (byte) 0x00;
        powerOff[7] = (byte) 0x00;
        powerOff[8] = (byte) 0x00;
        powerOff[9] = (byte) 0x01;
        powerOff[10] = (byte) 0x5D;
        powerOff[11] = (byte) 0x01;
        powerOff[12] = (byte) 0x00;
        powerOff[13] = (byte) 0x00;
        powerOff[14] = (byte) 0x6B;


        //开机
        byte powerOn[] = new byte[15];
        powerOn[0] = (byte) 0xFF;
        powerOn[1] = (byte) 0xFF;
        powerOn[2] = (byte) 0x0C;
        powerOn[3] = (byte) 0x00;
        powerOn[4] = (byte) 0x00;
        powerOn[5] = (byte) 0x00;
        powerOn[6] = (byte) 0x00;
        powerOn[7] = (byte) 0x00;
        powerOn[8] = (byte) 0x00;
        powerOn[9] = (byte) 0x01;
        powerOn[10] = (byte) 0x5D;
        powerOn[11] = (byte) 0x01;
        powerOn[12] = (byte) 0x00;
        powerOn[13] = (byte) 0x01;
        powerOn[14] = (byte) 0x6C;
        //启动
        byte powerStart[] = new byte[15];
        powerStart[0] = (byte) 0xFF;
        powerStart[1] = (byte) 0xFF;
        powerStart[2] = (byte) 0x0C;
        powerStart[3] = (byte) 0x00;
        powerStart[4] = (byte) 0x00;
        powerStart[5] = (byte) 0x00;
        powerStart[6] = (byte) 0x00;
        powerStart[7] = (byte) 0x00;
        powerStart[8] = (byte) 0x00;
        powerStart[9] = (byte) 0x01;
        powerStart[10] = (byte) 0x5D;
        powerStart[11] = (byte) 0x21;
        powerStart[12] = (byte) 0x00;
        powerStart[13] = (byte) 0x01;
        powerStart[14] = (byte) 0x8C;
        //查询数据
        byte getData2[] = new byte[13];
        getData2[0] = (byte) 0xFF;
        getData2[1] = (byte) 0xFF;
        getData2[2] = (byte) 0x0A;
        getData2[3] = (byte) 0x00;
        getData2[4] = (byte) 0x00;
        getData2[5] = (byte) 0x00;
        getData2[6] = (byte) 0x00;
        getData2[7] = (byte) 0x00;
        getData2[8] = (byte) 0x00;
        getData2[9] = (byte) 0x01;
        getData2[10] = (byte) 0x4D;
        getData2[11] = (byte) 0x01;
        getData2[12] = (byte) 0x59;
        byte checkData[] = new byte[11];
        checkData[0] = (byte) 0xFF;
        checkData[1] = (byte) 0xFF;
        checkData[2] = (byte) 0x08;
        checkData[3] = (byte) 0x00;
        checkData[4] = (byte) 0x00;
        checkData[5] = (byte) 0x00;
        checkData[6] = (byte) 0x00;
        checkData[7] = (byte) 0x00;
        checkData[8] = (byte) 0x00;
        checkData[9] = (byte) 0x73;
        checkData[10] = (byte) 0x7B;
        try {
            databackStream = dataBackSocket.getOutputStream();
            databackStreamHex = socketHex.getOutputStream();
            if (databackWriter == null)
                databackWriter = new PrintWriter(databackStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("-----------------接收数据消息中-----------------");
        //接收消息
        for (Map.Entry<String, String> entity : GlobalVariable.testingUnitsID.entrySet()) {
            System.out.println("GlobalVariable.testingUnitsID.size():" + GlobalVariable.testingUnitsID.size());
            System.out.println("GlobalVariable.testSatus.size():" + GlobalVariable.testSatus.size());
            Integer currentTestUnitID = Integer.parseInt(entity.getKey());//当前正在测试的台位号
            String currentModelAndType = entity.getValue();//当前测试的台位所对应的洗衣机类型
            try {
                InputStream input = dataReaders.get(currentTestUnitID);
                if (input == null) {
                    continue;
                }
                readCount = input.available();
                System.out.println("readCount:" + readCount);
                if (readCount > 0) {
                    readCount = dataReaders.get(currentTestUnitID).read(readBuffer);
                }
            } catch (SocketTimeoutException e) {
                e.printStackTrace();
                WriteLog.write(e.toString(), currentTestUnitID);
                System.out.println("--------------------SocketTimeoutException------------------");
                WriteLog.write("--------------------SocketTimeoutException------------------", currentTestUnitID);
                //捕获到超时信息，马上继续执行
                continue;
            } catch (SocketException e) {
                e.printStackTrace();
                WriteLog.write(e.toString(), currentTestUnitID);
                System.out.println("--------------------SocketException------------------");
                WriteLog.write("--------------------SocketException------------------", currentTestUnitID);
                //捕获到连接异常，重新进行初始化
                reInit(currentTestUnitID);
            } catch (IOException e) {
                e.printStackTrace();
                WriteLog.write(e.toString(), currentTestUnitID);
                WriteLog.write( "第" + currentTestUnitID + "个设备采集异常！", currentTestUnitID);
                System.out.println("--------------------尝试新建Socket连接----------------");
                WriteLog.write("--------------------尝试新建Socket连接----------------", currentTestUnitID);
                //一旦发生采集异常本台位的采集信息会停止，需要重新开测
                try {
                    connections.get(currentTestUnitID).close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                reInit(currentTestUnitID);
            } catch (Exception e) {
                e.printStackTrace();
            }
            collectedValue = HexString.parseString(readBuffer, readCount).trim();
            collectedValue = collectedValue.replaceAll(" +", " ");
            if(collectedValue!=null&&collectedValue.trim()!=""&&!collectedValue.contains("FF FF")){
                resultHex = "!Hex#" + "UNITID:" + currentTestUnitID + "#" + collectedValue;
                try {
                    databackStreamHex.write(resultHex.getBytes());
                    databackStreamHex.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
            //去掉FF 55的情况
            System.out.println(format.format(new Date()) + "台位:" + currentTestUnitID + ">>>>>>>>>>>>收集到数据:>>>>>>>>>>>>>>>" + collectedValue);
            WriteLog.write( "台位:" + currentTestUnitID + ">>>>>>>>>>>>收集到数据:>>>>>>>>>>>>>>>" + collectedValue, currentTestUnitID);
            String responses[] = collectedValue.split("FF FF");
            //去掉空格,同时将FF 55替换成FF
            for (int j = 1; j < responses.length; j++) {
                responses[j] = responses[j].trim();
                responses[j] = responses[j].replaceAll("FF 55", "FF");
            }
            for (int responseCount = 1; responseCount < responses.length; responseCount++) {
                System.out.println(format.format(new Date()) + "台位" + currentTestUnitID + ">>>>>>>>>>>输出第" + responseCount + "条采集数据:>>>>>>>>>>>>>>" + responses[responseCount]);
                WriteLog.write("台位" + currentTestUnitID + ">>>>>>>>>>>输出第" + responseCount + "条采集数据:>>>>>>>>>>>>>>" + responses[responseCount], currentTestUnitID);
                /*****/
                resultHex = "!Hex#" + "UNITID:" + currentTestUnitID + "#" + "FF FF " + responses[responseCount];
                try {
                    databackStreamHex.write(resultHex.getBytes());
                    databackStreamHex.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                /*****/
                //判断是否是C1 D12G3LU1型号 发命令FF FF 0C 00 00 00 00 00 00 F1 00 00 00 50 4D
                //滚筒
                //wifi确认信号
                byte command[] = new byte[15];
                command[0] = (byte) 0xFF;
                command[1] = (byte) 0xFF;
                command[2] = (byte) 0x0C;
                command[3] = (byte) 0x00;
                command[4] = (byte) 0x00;
                command[5] = (byte) 0x00;
                command[6] = (byte) 0x00;
                command[7] = (byte) 0x00;
                command[8] = (byte) 0x00;
                command[9] = (byte) 0xF1;
                command[10] = (byte) 0x00;
                command[11] = (byte) 0x00;
                command[12] = (byte) 0x00;
                command[13] = (byte) 0x50;
                command[14] = (byte) 0x4D;

                //接收到命令停止发送命令的指令
                byte getData[] = new byte[11];
                getData[0] = (byte) 0xFF;
                getData[1] = (byte) 0xFF;
                getData[2] = (byte) 0x08;
                getData[3] = (byte) 0x00;
                getData[4] = (byte) 0x00;
                getData[5] = (byte) 0x00;
                getData[6] = (byte) 0x00;
                getData[7] = (byte) 0x00;
                getData[8] = (byte) 0x00;
                getData[9] = (byte) 0x09;
                getData[10] = (byte) 0x11;
                try {
                    commandWriters.get(currentTestUnitID).write(command);
                    if (responses[responseCount].trim().length() > 40) {
                        String responseType = responses[responseCount].substring(24, 29);
                        //波轮
                        if (currentModelAndType.equals("1")) {
                            if (responseType.equals("7D 01")) {
                                String pulsator7D[] = responses[responseCount].trim().split(" ");
                                if (pulsator7D.length > 15) {
                                    result7D = new Pulsator().get7DData("FF FF " + responses[responseCount].trim());
                                    String pluster7DTemp = "FF FF " + responses[responseCount].trim();
                                    String pluster7D = pluster7DTemp.split(" ")[18];//运行阶段的程序（当前的洗衣程序）
                                    //String waterHeight = pluster7DTemp.split(" ")[36];
                                    result7D = "!DATA#" + "UNITID:" + currentTestUnitID + "#" + result7D;
                                    //boolean flag = true;
                                    if (result7D.contains("洗涤")) {
                                        waterHeight = pluster7DTemp.split(" ")[36];
                                    }
                                    if (Pulsator.openfeign == false) {
                                        //设置当前的洗衣程序  FF FF 0C 00 00 00 00 00 00 01 5D 02 00 mingling 6B
                                        if (GlobalVariable.testSatus.get(String.valueOf(currentTestUnitID)) == 0) {
                                            byte[] washProgram = new byte[15];
                                            washProgram[0] = (byte) 0xFF;
                                            washProgram[1] = (byte) 0xFF;
                                            washProgram[2] = (byte) 0x0C;
                                            washProgram[3] = (byte) 0x00;
                                            washProgram[4] = (byte) 0x00;
                                            washProgram[5] = (byte) 0x00;
                                            washProgram[6] = (byte) 0x00;
                                            washProgram[7] = (byte) 0x00;
                                            washProgram[8] = (byte) 0x00;
                                            washProgram[9] = (byte) 0x01;
                                            washProgram[10] = (byte) 0x5D;
                                            washProgram[11] = (byte) 0x02;
                                            washProgram[12] = (byte) 0x00;
                                            washProgram[13] = (byte) Integer.parseInt(pluster7D, 16);//洗衣程序
                                            //计算校验和
                                            String checkNum = "0C 00 00 00 00 00 00 01 5D 02 00 " + pluster7D;
                                            String checkNumResult = CheckSum.makeCheckSum(checkNum);
                                            washProgram[14] = (byte) Integer.parseInt(checkNumResult, 16);//校验和
                                            //设置水位  FF FF 0C 00 00 00 00 00 00 01 5D 05 00 mingling 6B
                                            byte[] water = new byte[15];
                                            if (waterHeight != null) {
                                                water[0] = (byte) 0xFF;
                                                water[1] = (byte) 0xFF;
                                                water[2] = (byte) 0x0C;
                                                water[3] = (byte) 0x00;
                                                water[4] = (byte) 0x00;
                                                water[5] = (byte) 0x00;
                                                water[6] = (byte) 0x00;
                                                water[7] = (byte) 0x00;
                                                water[8] = (byte) 0x00;
                                                water[9] = (byte) 0x01;
                                                water[10] = (byte) 0x5D;
                                                water[11] = (byte) 0x05;
                                                water[12] = (byte) 0x00;
                                                water[13] = (byte) Integer.parseInt(waterHeight, 16);//水位高度
                                                //计算校验和
                                                String checkNum2 = "0C 00 00 00 00 00 00 01 5D 05 00 " + waterHeight;
                                                String checkNumResult2 = CheckSum.makeCheckSum(checkNum2);
                                                water[14] = (byte) Integer.parseInt(checkNumResult2, 16);//校验和
                                            }
                                            boolean flagPlustor = true;
                                            int plustorInteger = 0;
                                            while (flagPlustor && plustorInteger < 3) {
                                                plustorInteger++;
                                                for (int i = 0; i < 5; i++) {
                                                    commandWriters.get(currentTestUnitID).write(powerOff);
                                                    commandWriters.get(currentTestUnitID).flush();
                                                    Thread.sleep(200);
                                                    System.out.println("台位:" + currentTestUnitID + "------发送关机程序命令中------");
                                                    WriteLog.write("台位:" + currentTestUnitID + "------发送关机程序命令中------", currentTestUnitID);

                                                }
                                                for (int i = 0; i < 5; i++) {
                                                    commandWriters.get(currentTestUnitID).write(powerOn);
                                                    commandWriters.get(currentTestUnitID).flush();
                                                    Thread.sleep(200);
                                                    System.out.println("台位:" + currentTestUnitID + "------发送开机命令中------");
                                                    WriteLog.write("台位:" + currentTestUnitID + "------发送开机命令中------", currentTestUnitID);
                                                }

                                                //设置洗衣程序
                                                for (int i = 0; i < 5; i++) {
                                                    commandWriters.get(currentTestUnitID).write(washProgram);
                                                    commandWriters.get(currentTestUnitID).flush();
                                                    Thread.sleep(200);
                                                    System.out.println("台位:" + currentTestUnitID + "------发送设定洗衣程序命令中------");
                                                    WriteLog.write("台位:" + currentTestUnitID + "------发送设定洗衣程序命令中------", currentTestUnitID);

                                                }
                                                if (waterHeight != null) {
                                                    //设置水位
                                                    for (int i = 0; i < 5; i++) {
                                                        commandWriters.get(currentTestUnitID).write(water);
                                                        commandWriters.get(currentTestUnitID).flush();
                                                        Thread.sleep(200);
                                                        System.out.println("台位:" + currentTestUnitID + "------发送设定水位命令中------");
                                                        WriteLog.write("台位:" + currentTestUnitID + "------发送设定水位命令中------", currentTestUnitID);
                                                    }
                                                }

                                                //启动
                                                for (int i = 0; i < 5; i++) {
                                                    commandWriters.get(currentTestUnitID).write(powerStart);
                                                    commandWriters.get(currentTestUnitID).flush();
                                                    Thread.sleep(200);
                                                    System.out.println("台位:" + currentTestUnitID + "------发送启动程序命令中------");
                                                    WriteLog.write("台位:" + currentTestUnitID + "------发送启动程序命令中------", currentTestUnitID);
                                                }

                                                //查询
                                                commandWriters.get(currentTestUnitID).write(getData2);
                                                commandWriters.get(currentTestUnitID).flush();
                                                InputStream input = dataReaders.get(currentTestUnitID);
                                                readCount = input.available();
                                                System.out.println("readCount:" + readCount);
                                                if (readCount > 0) {
                                                    readCount = dataReaders.get(currentTestUnitID).read(readBuffer);
                                                }
                                                String collectedValueTest = HexString.parseString(readBuffer, readCount).trim();
                                                collectedValueTest = collectedValueTest.replaceAll(" +", " ");
                                                //去掉FF 55的情况
                                                String receive[] = collectedValueTest.split("FF FF");
                                                //去掉空格,同时将FF 55替换成FF
                                                for (int j = 1; j < receive.length; j++) {
                                                    receive[j] = receive[j].trim();
                                                    receive[j] = receive[j].replaceAll("FF 55", "FF");
                                                }
                                                for (int i = 1; i < receive.length; i++) {
                                                    String Type = receive[i].substring(24, 29);
                                                    if (Type.equals("6D 01") || Type.equals("7D 01")) {
                                                        String machineStatus = receive[i].substring(42, 44);
                                                        if (!machineStatus.equals("00") && !machineStatus.equals("0E")) {
                                                            flagPlustor = false;
                                                            plustorInteger = 0;
                                                        } else {
                                                            flagPlustor = true;
                                                        }
                                                    }
                                                }

                                            }

                                            GlobalVariable.testSatus.put(String.valueOf(currentTestUnitID), 1);
                                        }
                                    } else {
                                        GlobalVariable.testSatus.put(String.valueOf(currentTestUnitID), 0);
                                    }
                                } else {
                                    System.out.println("------------接收的波轮洗衣机数据不完整----------------");
                                }
                            }
                            if (responseType.equals("0F 5A")) {
                                String pulsatorAlarm[] = responses[responseCount].trim().split(" ");
                                if (pulsatorAlarm.length == 15) {
                                    String alarmcode = "FF FF " + responses[responseCount].trim();
                                    alarm = new Pulsator().getAlarm(alarmcode);
                                    alarm = "!ALARM#" + "UNITID:" + currentTestUnitID + "#" + alarm + "#" + alarmcode;
                                    commandWriters.get(currentTestUnitID).write(getData);
                                    commandWriters.get(currentTestUnitID).flush();
                                    if (!alarm.contains("报警解除")) {
                                        databackStream.write(alarm.getBytes());
                                        databackStream.flush();
                                        System.out.println("返回报警信息:" + alarm);
                                        WriteLog.write("返回报警信息:" + alarm, currentTestUnitID);
                                    }
                                }
                            }
                        }
                        //滚筒
                        if (currentModelAndType.equals("2")) {
                            if (responseType.equals("7D 01")) {
                                date7DTemp = responses[responseCount].trim();
                                String roller7DSize[] = date7DTemp.split(" ");
                                if (roller7DSize.length >= 15) {
                                    result7D = new Roller().get7DData("FF FF " + date7DTemp);
                                    String resultRoller = "FF FF " + date7DTemp;
                                    //String roller7D = resultRoller.split(" ")[12];
                                    result7D = "!DATA#" + "UNITID:" + currentTestUnitID + "#" + result7D;
                                    if (result7D.contains("结束")) {
                                        //找出洗衣程序
                                        roller7D = resultRoller.split(" ")[12];
                                    }
                                    if (result7D.contains("待机")) {
                                        for (int i = 0; i < 5; i++) {
                                            commandWriters.get(currentTestUnitID).write(powerOn);
                                            commandWriters.get(currentTestUnitID).flush();
                                            Thread.sleep(200);
                                            System.out.println("台位:" + currentTestUnitID + "------发送开机命令中------");
                                            WriteLog.write("台位:" + currentTestUnitID + "------发送开机命令中------", currentTestUnitID);
                                        }
                                        if (roller7D != null) {
                                            for (int i = 0; i < 5; i++) {
                                                //设置当前的洗衣程序  FF FF 0C 00 00 00 00 00 00 01 5D 03 00 mingling 6B
                                                byte[] washProgram = new byte[15];
                                                washProgram[0] = (byte) 0xFF;
                                                washProgram[1] = (byte) 0xFF;
                                                washProgram[2] = (byte) 0x0C;
                                                washProgram[3] = (byte) 0x00;
                                                washProgram[4] = (byte) 0x00;
                                                washProgram[5] = (byte) 0x00;
                                                washProgram[6] = (byte) 0x00;
                                                washProgram[7] = (byte) 0x00;
                                                washProgram[8] = (byte) 0x00;
                                                washProgram[9] = (byte) 0x01;
                                                washProgram[10] = (byte) 0x5D;
                                                washProgram[11] = (byte) 0x03;
                                                washProgram[12] = (byte) 0x00;
                                                washProgram[13] = (byte) Integer.parseInt(roller7D, 16);//洗衣程序
                                                //计算校验和
                                                String checkNum = "0C 00 00 00 00 00 00 01 5D 03 00 " + roller7D;
                                                String checkNumResult = CheckSum.makeCheckSum(checkNum);
                                                washProgram[14] = (byte) Integer.parseInt(checkNumResult, 16);//校验和
                                                //设置洗衣程序
                                                commandWriters.get(currentTestUnitID).write(washProgram);
                                                commandWriters.get(currentTestUnitID).flush();
                                                Thread.sleep(200);
                                                System.out.println("台位:" + currentTestUnitID + "------发送设定洗衣程序命令中------");
                                                WriteLog.write("台位:" + currentTestUnitID + "------发送设定洗衣程序命令中------", currentTestUnitID);
                                            }

                                        }
                                        //启动洗衣机
                                        for (int i = 0; i < 5; i++) {
                                            commandWriters.get(currentTestUnitID).write(powerStart);
                                            commandWriters.get(currentTestUnitID).flush();
                                            System.out.println("台位:" + currentTestUnitID + "------发送启动程序命令中------");
                                            WriteLog.write("台位:" + currentTestUnitID + "------发送启动程序命令中------", currentTestUnitID);
                                            Thread.sleep(200);
                                        }
                                    }
                                    if (Roller.openFlag == false) {
                                        if (GlobalVariable.testSatus.get(String.valueOf(currentTestUnitID)) == 0) {
                                            //设置当前的洗衣程序  FF FF 0C 00 00 00 00 00 00 01 5D 03 00 mingling 6B
                                            byte[] washProgram = new byte[15];
                                            washProgram[0] = (byte) 0xFF;
                                            washProgram[1] = (byte) 0xFF;
                                            washProgram[2] = (byte) 0x0C;
                                            washProgram[3] = (byte) 0x00;
                                            washProgram[4] = (byte) 0x00;
                                            washProgram[5] = (byte) 0x00;
                                            washProgram[6] = (byte) 0x00;
                                            washProgram[7] = (byte) 0x00;
                                            washProgram[8] = (byte) 0x00;
                                            washProgram[9] = (byte) 0x01;
                                            washProgram[10] = (byte) 0x5D;
                                            washProgram[11] = (byte) 0x03;
                                            washProgram[12] = (byte) 0x00;
                                            washProgram[13] = (byte) Integer.parseInt(roller7D, 16);//洗衣程序
                                            //计算校验和
                                            String checkNum = "0C 00 00 00 00 00 00 01 5D 03 00 " + roller7D;
                                            String checkNumResult = CheckSum.makeCheckSum(checkNum);
                                            washProgram[14] = (byte) Integer.parseInt(checkNumResult, 16);//校验和

                                            //取出当前的洗衣程序
                                            boolean rollerFlag = true;
                                            int rollerInteger = 0;
                                            while (rollerFlag && rollerInteger < 3) {
                                                rollerInteger++;
                                                System.out.println("进入重启中.....................");
                                                WriteLog.write("进入重启中.....................", currentTestUnitID);
                                                for (int i = 0; i < 5; i++) {
                                                    commandWriters.get(currentTestUnitID).write(powerOff);
                                                    commandWriters.get(currentTestUnitID).flush();
                                                    Thread.sleep(200);
                                                    System.out.println("台位:" + currentTestUnitID + "------发送关机命令中------");
                                                    WriteLog.write("台位:" + currentTestUnitID + "------发送关机命令中------", currentTestUnitID);
                                                }
                                                for (int i = 0; i < 5; i++) {
                                                    commandWriters.get(currentTestUnitID).write(powerOn);
                                                    commandWriters.get(currentTestUnitID).flush();
                                                    Thread.sleep(200);
                                                    System.out.println("台位:" + currentTestUnitID + "------发送开机命令中------");
                                                    WriteLog.write("台位:" + currentTestUnitID + "------发送开机命令中------", currentTestUnitID);
                                                }
                                                for (int i = 0; i < 5; i++) {
                                                    commandWriters.get(currentTestUnitID).write(washProgram);
                                                    commandWriters.get(currentTestUnitID).flush();
                                                    Thread.sleep(200);
                                                    System.out.println("台位:" + currentTestUnitID + "------发送设定洗衣程序命令中------");
                                                    WriteLog.write("台位:" + currentTestUnitID + "------发送设定洗衣程序命令中------", currentTestUnitID);
                                                }
                                                for (int i = 0; i < 5; i++) {
                                                    commandWriters.get(currentTestUnitID).write(powerStart);
                                                    commandWriters.get(currentTestUnitID).flush();
                                                    System.out.println("台位:" + currentTestUnitID + "------发送启动程序命令中------");
                                                    WriteLog.write("台位:" + currentTestUnitID + "------发送启动程序命令中------", currentTestUnitID);
                                                    Thread.sleep(200);
                                                }
                                                //查询
                                                commandWriters.get(currentTestUnitID).write(getData2);
                                                commandWriters.get(currentTestUnitID).flush();
                                                InputStream input = dataReaders.get(currentTestUnitID);
                                                readCount = input.available();
                                                System.out.println("readCount:" + readCount);
                                                if (readCount > 0) {
                                                    readCount = dataReaders.get(currentTestUnitID).read(readBuffer);
                                                }
                                                String collectedValueTest = HexString.parseString(readBuffer, readCount).trim();
                                                collectedValueTest = collectedValueTest.replaceAll(" +", " ");
                                                //去掉FF 55的情况
                                                String receive[] = collectedValueTest.split("FF FF");
                                                //去掉空格,同时将FF 55替换成FF
                                                for (int j = 1; j < receive.length; j++) {
                                                    receive[j] = receive[j].trim();
                                                    receive[j] = receive[j].replaceAll("FF 55", "FF");
                                                }
                                                for (int m = 1; m < receive.length; m++) {
                                                    String Type = receive[m].substring(24, 29);
                                                    if (Type.equals("6D 01") || Type.equals("7D 01")) {
                                                        String machineStatus = receive[m].substring(42, 44);
                                                        if (!machineStatus.equals("00") && !machineStatus.equals("0E")) {
                                                            rollerFlag = false;
                                                            rollerInteger = 0;
                                                        } else {
                                                            rollerFlag = true;
                                                        }
                                                    }
                                                }
                                            }
                                            GlobalVariable.testSatus.put(String.valueOf(currentTestUnitID), 1);
                                        }
                                    } else {
                                        GlobalVariable.testSatus.put(String.valueOf(currentTestUnitID), 0);
                                    }

                                }

                            }
                            if (responseType.equals("0F 5A")) {
                                String rollerAlarm[] = responses[responseCount].trim().split(" ");
                                if (rollerAlarm.length == 23) {
                                    String alarmcode = "FF FF " + responses[responseCount].trim();
                                    alarm = new Roller().getAlarm(alarmcode);
                                    alarm = "!ALARM#" + "UNITID:" + currentTestUnitID + "#" + alarm +"#"+alarmcode;
                                    //只要接受到报警信息就发送命令不让其继续上报
                                    commandWriters.get(currentTestUnitID).write(getData);
                                    commandWriters.get(currentTestUnitID).flush();
                                    if (!alarm.contains("报警解除")) {
                                        databackStream.write(alarm.getBytes());
                                        databackStream.flush();
                                        System.out.println("返回报警信息:" + alarm);
                                        WriteLog.write("返回报警信息:" + alarm, currentTestUnitID);
                                    }
                                }
                            }
                        }
                        //干衣机
                        if (currentModelAndType.equals("3")) {
                            if (responseType.equals("7D 01")) {
                                date7DTemp = responses[responseCount].trim();
                                String roller7DSize[] = date7DTemp.split(" ");
                                if (roller7DSize.length >= 54) {
                                    result7D = new Dryer().get7DData("FF FF " + date7DTemp);
                                    result7D = "!DATA#" + "UNITID:" + currentTestUnitID + "#" + result7D;
                                }

                            }
                            if (responseType.equals("0F 5A")) {
                                String rollerAlarm[] = responses[responseCount].trim().split(" ");
                                if (rollerAlarm.length == 23) {
                                    alarm = new Dryer().getAlarm("FF FF " + responses[responseCount]);
                                    alarm = "!ALARM#" + "UNITID:" + currentTestUnitID + "#" + alarm;
                                    //只要接受到报警信息就发送命令不让其继续上报
                                    commandWriters.get(currentTestUnitID).write(getData);
                                    commandWriters.get(currentTestUnitID).flush();
                                    if (!alarm.contains("报警解除")) {
                                        databackStream.write(alarm.getBytes());
                                        databackStream.flush();
                                        System.out.println("返回报警信息:" + alarm);
                                        WriteLog.write("返回报警信息:" + alarm, currentTestUnitID);
                                    }
                                }
                            }
                        }
                    } else {
                        System.out.println("---------------接收到命令缺少7D跟alarm的标识位信息-------------------");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (!result7D.equals("")) {
                try {

                    databackStream.write(result7D.getBytes());
                    databackStream.flush();
                    System.out.println("解析后的数据:"+result7D);
                    result7D = "";
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        //发送消息
        for (Map.Entry<String, String> entity1 : GlobalVariable.testingUnitsID.entrySet()) {
            Integer currentTestUnitID1 = Integer.parseInt(entity1.getKey());//当前正在测试的台位号
            TestingMachine tempMachine = machines.get(currentTestUnitID1);
            if (connections.get(currentTestUnitID1) == null) {
                try {
                    Socket tempConnection = new Socket();
                    if (tempMachine == null) {
                        continue;
                    }
                    InetSocketAddress addr = new InetSocketAddress(tempMachine.getIP(), Integer.parseInt(tempMachine.getPort()));
                    tempConnection.connect(addr, 200);
                    tempConnection.setSoTimeout(200);
                    tempConnection.setKeepAlive(true);
                    connections.remove(currentTestUnitID1);
                    connections.put(currentTestUnitID1, tempConnection);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println(format.format(new Date()) + "第" + currentTestUnitID1 + "个设备无法建立socket连接！");
                    WriteLog.write("第" + currentTestUnitID1 + "个设备无法建立socket连接！", currentTestUnitID1);
                    reInit(currentTestUnitID1);
                    continue;
                }
            }
            if (commandWriters.get(currentTestUnitID1) == null) {
                try {
                    OutputStream tempWriter = connections.get(currentTestUnitID1).getOutputStream();
                    commandWriters.remove(currentTestUnitID1);
                    commandWriters.put(currentTestUnitID1, tempWriter);
                } catch (SocketException e) {
                    e.printStackTrace();
                    WriteLog.write(e.toString(), currentTestUnitID1);
                    WriteLog.write("台位" + currentTestUnitID1 + "重新进行初始化", currentTestUnitID1);
                    reInit(currentTestUnitID1);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println(format.format(new Date()) + "第" + currentTestUnitID1 + "个设备无法打开输出流！");
                    WriteLog.write( "第" + currentTestUnitID1 + "个设备无法打开输出流！", currentTestUnitID1);
                    continue;
                }
            }
            if (dataReaders.get(currentTestUnitID1) == null) {
                try {
                    InputStream tempReader = connections.get(currentTestUnitID1).getInputStream();
                    dataReaders.remove(currentTestUnitID1);
                    dataReaders.put(currentTestUnitID1, tempReader);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println(format.format(new Date()) + "第" + currentTestUnitID1 + "个设备无法打开输入流！");
                    WriteLog.write( "第" + currentTestUnitID1 + "个设备无法打开输出流！", currentTestUnitID1);
                    continue;
                }
            }

            try {

                System.out.println("-------" + commandWriters.get(currentTestUnitID1));
                if(flagTrue == false){
                    commandWriters.get(currentTestUnitID1).write(getData2);
                    commandWriters.get(currentTestUnitID1).flush();
                }else{
                    commandWriters.get(currentTestUnitID1).write(checkData);
                    commandWriters.get(currentTestUnitID1).flush();
                }


            } catch (SocketTimeoutException e) {
                System.out.println("--------------------台位:" + currentTestUnitID1 + "的SocketTimeoutException------------------");
                WriteLog.write("--------------------台位:" + currentTestUnitID1 + "的SocketTimeoutException------------------", currentTestUnitID1);
                e.printStackTrace();
                //捕获到超时信息，马上继续执行
                continue;
            } catch (SocketException e) {
                e.printStackTrace();
                //捕获到连接异常，重新进行初始化
                WriteLog.write(e.toString(), currentTestUnitID1);
                System.out.println("--------------------台位" + currentTestUnitID1 + "的SocketException------------------");
                WriteLog.write("--------------------台位" + currentTestUnitID1 + "的SocketException------------------", currentTestUnitID1);
                reInit(currentTestUnitID1);
            } catch (IOException e) {
                e.printStackTrace();
                WriteLog.write(e.toString(), currentTestUnitID1);
                System.out.println(format.format(new Date()) + "第" + currentTestUnitID1 + "个设备采集异常！");
                WriteLog.write( "第" + currentTestUnitID1 + "个设备采集异常！", currentTestUnitID1);
                System.out.println("--------------------尝试新建Socket连接----------------");
                WriteLog.write("--------------------尝试新建Socket连接----------------", currentTestUnitID1);

                //一旦发生采集异常本台位的采集信息会停止，需要重新开测
                try {
                    connections.get(currentTestUnitID1).close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                reInit(currentTestUnitID1);
                //continue;
            }
        }
        if (flagTrue == false){
            flagTrue = true;
        }else{
            flagTrue = false;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    //使用多线程进行接收数据
    public void run() {
        try {
            ServerSocket
                    dataBackServer = new ServerSocket(7002);

            dataBackSocket = dataBackServer.accept();
            if (dataBackSocket != null) {
                System.out.println("端口7002初始化成功");
            }
            //打开7003端口用来返回原始数据
            serverSocketHex = new ServerSocket(7003);
            socketHex = serverSocketHex.accept();
            if (socketHex != null) {
                System.out.println("端口7003初始化成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            byte info[] = new byte[4096];
            InputStream inputStream = dataBackSocket.getInputStream();
            while (true) {
                try {
                    int readCount = inputStream.available();
                    if (readCount > 0) {
                        int s = inputStream.read(info);
                        String s1 = new String(info, 0, readCount);
                        System.out.println(format.format(new Date()) + "接受到的数据：" + s1);
                        getMsg();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        MainControl m = MainControl.getMainControl();
        System.out.println("-----------准备就绪,请开启主控----------");
        Thread t = new Thread(m);
        CommandControl c = CommandControl.getInstance();
        Thread t1 = new Thread(c);
        t1.start();
        t.start();
    }
}
